﻿using System;
using System.Linq;
using System.Web.Mvc;
using DDDSample.Application.Book;
using DDDSample.Application.HandlingEvent;
using DDDSample.Domain.HandlingEvent;
using DDDSample.Domain.Location;

namespace DDDSample.UI.Mvc.Controllers
{
    public class HandlingController : Controller
    {
        private readonly IBookService _bookService;
        private readonly IHandlingEventService _handlingEventService;

        public HandlingController(IHandlingEventService handlingEventService,IBookService bookService)
        {
            _handlingEventService = handlingEventService;
            _bookService = bookService;
        }

        [HttpGet]
        public ActionResult RegisterHandlingEvent(string id)
        {
            AddHandlingLocations();
            AddHandlingEventTypes();
            return View();
        }

        [HttpPost]
        public ActionResult RegisterHandlingEvent(string id, DateTime? completionTime, string location, HandlingEventType type)
        {
            var validationError = false;
            if (!completionTime.HasValue)
            {
                ViewData.ModelState.AddModelError("completionTime", @"Event completion date is required and must be a valid date.");
                validationError = true;
            }
            if (string.IsNullOrWhiteSpace(id))
            {
                ViewData.ModelState.AddModelError("id", @"Id must be specified.");
                validationError = true;
            }
            if (validationError)
            {
                AddHandlingLocations();
                AddHandlingEventTypes();
                return View();
            }
            _handlingEventService.RegisterHandlingEvent(completionTime.Value, Guid.Parse(id), new UnLocode(location), type);
            return RedirectToAction("Track", "Tracking", new { id });
        }

        private void AddHandlingLocations()
        {
            ViewData["location"] = _bookService.ListShippingLocations()
                .Select(x => new SelectListItem { Text = x.Name, Value = x.UnLocode.CodeString })
                .ToList();
        }

        private void AddHandlingEventTypes()
        {
            ViewData["type"] = Enum.GetNames(typeof(HandlingEventType))
               .Select(x => new SelectListItem { Text = x, Value = x });
        }
    }
}